<template>
  <div class="hw-editor" :style="`width: ${width}`">
    <toolbar style="border-bottom: 1px solid #ccc;"
             :editor="editorRef"
             :defaultConfig="toolbarConfig"
             :mode="mode"></toolbar>
    <editor :style="`height: ${height}; overflow:hidden`" v-model="valueHtml"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated" @onChange="onChanges"></editor>
  </div>
</template>

<script>
import "@wangeditor/editor/dist/css/style.css";
import {Editor, Toolbar} from "@wangeditor/editor-for-vue";
import { onBeforeUnmount, onMounted, ref, shallowRef } from "vue";
import {apiUrl} from "@/utils/ajax";

export default {
  components: {Editor, Toolbar},
  props: {
    height: {
      default: () => "300px"
    },
    width: {
      default: () => "65%"
    },
    its: {
      default: () => ""
    }
  },
  setup(props,contentText) {
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef();

    // 内容 HTML
    const valueHtml = ref(props.its);

    // 模拟 ajax 异步获取内容
    onMounted(() => {
      setTimeout(() => {
        valueHtml.value = props.its;
      }, 1500);
    });

    const toolbarConfig = {};
    const editorConfig = {
      placeholder: "请输入内容...",
      MENU_CONF: {
        uploadImage: {
          server: `${apiUrl}upload/uploadEditFile`,
          fieldName: "editor",
          headers: {
            Authorization: localStorage.getItem("account")
          },
          meta:{
            file_name: "editor"
          },
          // 单个文件上传失败
          onFailed(file, res) {
            console.log(res)
          },
        }
      }
    };

    const onChanges = () => {
      contentText.emit("editor", valueHtml);
    };

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.destroy();
    });

    const handleCreated = (editor) => {
      editorRef.value = editor; // 记录 editor 实例，重要！
    };

    return {
      editorRef,
      valueHtml,
      mode: "default", // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,
      onChanges
    };
  }
};
</script>

<style lang="less" scoped>
.hw-editor {
  border: 1px solid #dedede;
}
</style>
